<template>
  <el-dialog :visible.sync="infoVisible" width="450px" :close-on-click-modal="false" @closed="reset">
    <div slot="title" class="dialog-title">
      {{ isBinding ? "" : "新" }}{{ type === "phone" ? "手机号" : "邮箱" }}绑定
    </div>
    <el-form
      ref="updateForm"
      :model="updateForm"
      :rules="updateRules"
      label-position="top"
      size="medium"
      class="change-form"
      :hide-required-asterisk="true">
      <div class="form-item-label tips" v-if="!isBinding">
        验证成功，请验证新的{{ type === "phone" ? "手机号码" : "邮箱" }}
      </div>

      <el-form-item label="" prop="phoneNumber" v-if="type === 'phone'">
        <span slot="label" class="form-item-label" :class="{ 'red-color': accountError }">
          手机号码
          <span v-if="accountError" style="font-size: 0.9285em">（此手机号已被使用）</span>
        </span>
        <el-input v-model="updateForm.phoneNumber" autocomplete="off" :placeholder="placeholder1" />
      </el-form-item>
      <el-form-item label="" prop="email" v-if="type === 'email'">
        <span slot="label" class="form-item-label" :class="{ 'red-color': accountError }">
          邮箱
          <span v-if="accountError" style="font-size: 0.9285em">（此邮箱已被使用）</span>
        </span>
        <el-input v-model="updateForm.email" autocomplete="off" :placeholder="placeholder1"> </el-input>
      </el-form-item>
      <el-form-item label="" prop="authCode">
        <span slot="label" class="form-item-label" :class="{ 'red-color': codeError }">
          {{ type === "phone" ? "短信验证码" : "邮箱验证码" }}
          <span v-if="codeError" style="font-size: 0.9285em">（验证码错误）</span>
        </span>
        <el-input v-model="updateForm.authCode" :placeholder="placeholder2">
          <el-button slot="append" class="send-btn" @click="sendCode" :disabled="validateCodeBtn">{{
            validateCodeBtnText
          }}</el-button>
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="reset">取 消</el-button>
      <el-button type="primary" @click="submit">确认</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isExist, checkCode } from "@/api/system/user"
import { sendPhoneCode, sendEmailCode } from "@/api/system/verifyCode"
import { updateUserProfile } from "@/api/system/user"

export default {
  filters: {
    phoneFilter(val) {
      let reg = /^(.{3}).*(.{4})$/
      return val.replace(reg, "$1****$2")
    },
    emailFilter(val) {
      let reg = /^(.{3}).*(.{6})$/
      return val.replace(reg, "$1****$2")
    },
  },
  data() {
    return {
      type: "",
      updateForm: {
        phoneNumber: "",
        email: "",
        authCode: "",
      },
      validateAccount: false,
      isBinding: false,
      placeholder1: "",
      placeholder2: "",
      validateCodeBtn: false,
      validateCodeBtnText: "",
      accountError: false,
      codeError: false,
      infoVisible: false,
      updateRules: {
        phoneNumber: [
          { required: true, trigger: "blur", message: "请输入手机号" },
          {
            pattern: /^(?:0|86|\+86)?1[3456789]\d{9}$/,
            message: "请输入正确的手机号",
          },
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入邮箱" },
          {
            pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: "请输入正确的邮箱",
          },
        ],
        authCode: [{ required: true, trigger: "blur", message: "请输入验证码" }],
      },
    }
  },
  methods: {
    bind(type) {
      this.isBinding = true
      this.doUpdate(type)
    },
    doUpdate(type) {
      if (type === "phone") {
        this.validateCodeBtnText = "发送短信验证码"
        this.placeholder1 = "请输入要验证的手机号码"
        this.placeholder2 = "请输入短信验证码"
      } else if (type === "email") {
        this.validateCodeBtnText = "发送邮箱验证码"
        this.placeholder1 = "请输入要验证的邮箱"
        this.placeholder2 = "请输入邮箱验证码"
      }
      this.type = type
      this.infoVisible = true
    },
    sendCode() {
      let validate = this.type === "phone" ? "phoneNumber" : "email"
      this.$refs["updateForm"].validateField(validate, (err) => {
        if (!err) {
          isExist({
            type: this.type,
            account: this.updateForm[validate],
          }).then((res) => {
            if (!res.data) {
              this.accountError = false
              this.validateAccount = true
              if (this.type === "phone") {
                sendPhoneCode(this.updateForm.phoneNumber).then(() => {
                  this.doBtnControl()
                })
              } else if (this.type === "email") {
                sendEmailCode(this.updateForm.email).then(() => {
                  this.doBtnControl()
                })
              }
            } else {
              this.accountError = true
            }
          })
        }
      })
    },
    // 表单重置
    reset() {
      this.accountError = false
      this.codeError = false
      this.infoVisible = false
      this.validateAccount = false
      this.isBinding = false
      this.resetForm("updateForm")
    },
    submit() {
      if (!this.validateAccount) {
        this.$modal.msgError("先获取验证码")
        return
      }
      this.$refs["updateForm"].validateField("authCode", (err) => {
        if (!err) {
          let codeType = this.type === "phone" ? "CodePhone" : "CodeEmail"
          checkCode({
            phoneNumber: this.updateForm.phoneNumber,
            email: this.updateForm.email,
            code: this.updateForm.authCode,
            type: codeType,
          }).then((res) => {
            if (res.data) {
              if (this.type === "phone") {
                updateUserProfile({
                  phoneNumber: this.updateForm.phoneNumber,
                }).then((response) => {
                  this.$modal.msgSuccess(this.isBinding ? "手机号绑定成功" : "手机号更换成功")
                  this.$emit("updateInfo", "phoneNumber", this.updateForm.phoneNumber)
                  this.reset()
                })
              } else if (this.type === "email") {
                updateUserProfile({ email: this.updateForm.email }).then((response) => {
                  this.$emit("updateInfo", "email", this.updateForm.email)
                  this.$modal.msgSuccess(this.isBinding ? "邮箱绑定成功" : "邮箱更换成功")
                  this.reset()
                })
              }
            } else {
              this.codeError = true
            }
          })
        }
      })
    },
    doBtnControl() {
      this.validateCodeBtn = true
      this.$modal.msgSuccess("验证码发送成功，5分钟内有效")
      let count = 60
      let timer = setInterval(() => {
        count--
        this.validateCodeBtnText = count + "s后重新发送"
        if (count == 0) {
          if (this.type === "phone") {
            this.validateCodeBtnText = "发送短信验证码"
          } else if (this.type === "email") {
            this.validateCodeBtnText = "发送邮箱验证码"
          }
          this.validateCodeBtn = false
          clearInterval(timer)
        }
      }, 1000)
    },
  },
}
</script>

<style lang="scss" scoped>
.info-form {
  .el-input--medium {
    width: 25%;
  }
  .change-btn {
    margin-left: 10px;
  }
}

.dialog-title {
  color: #40485b;
  width: 100%;
  border-bottom: 1px solid #eee;
  position: absolute;
  left: 0;
  top: 0;
  padding: 15px;
  font-size: 1.143rem;
  font-weight: bold;
}

.change-form {
  .form-item-label {
    color: rgba(0, 0, 0, 0.8);
    font-size: 1em;
    font-weight: bold;
  }

  .red-color {
    color: #d95c5c;
  }

  .tips {
    margin: 1em 0em 1rem 0em;
  }
}

.send-btn {
  color: #fe7300 !important;
}
.mobile {
  color: #333;
}
</style>
